package com.ffcs.web.services;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ffcs.web.daos.implementations.WxUserDao;
import com.ffcs.web.model.dto.UserInfo;
import com.ffcs.web.model.entity.Order;
import com.ffcs.web.model.entity.WxUser;
import com.ffcs.web.utils.ChinaeseUtil;

@Service
public class WxUserService {

	private Logger logger = Logger.getLogger(WxUserService.class);
	
	@Autowired
	private WxUserDao wxUserDao;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	/**
	 * 保存微信用户信息
	 * @param userInfo
	 * @return
	 */
	@Transactional
	public WxUser saveUser(UserInfo userInfo) {
		
		List<WxUser> wxList=wxUserDao.findByPropertyName("openid",userInfo.getOpenid());
		if(wxList.size()>0){
			logger.info("微信用户已入库，直接返回openid="+userInfo.getOpenid());
			return wxList.get(0);
		}
		
		WxUser wxUser=new WxUser();
		wxUser.setCity(userInfo.getCity());
		wxUser.setCountry(userInfo.getCountry());
		wxUser.setHeadimgurl(userInfo.getHeadimgurl());
		wxUser.setLanguage(userInfo.getLanguage());
		wxUser.setNickname(userInfo.getNickname());
		wxUser.setOpenid(userInfo.getOpenid());
		wxUser.setPrivilege("");
		wxUser.setProvince(userInfo.getProvince());
		wxUser.setRegisterTime(new Date());
		wxUser.setLastLoginTime(new Date());
		wxUser.setStatus((short)0);
		wxUser.setIsConsume((short)0);
		wxUser.setConsumeTotal(0d);
		wxUser.setConsumeCounts(0);
		wxUser.setSex(Short.parseShort(userInfo.getSex()));
		wxUserDao.save(wxUser);
		logger.info("用户"+userInfo.getLanguage()+"插入数据库成功userId="+wxUser.getId());
		return wxUser;
	}
	
	/**
	 * 获取用户情况
	 * @param openid
	 * @return
	 */
	public String isAddUser(String openid) {
		List<WxUser> wxList=wxUserDao.findByPropertyName("openid",openid);
		if(wxList.size()>0){
			WxUser u=wxList.get(0);
			if(null!=u.getTelephone() && !"".equals(u.getTelephone())){
				logger.info("openid="+openid+"微信用户已入库，并且已经绑定");
				return "2";
			}else{
				logger.info("openid="+openid+"微信用户已入库，还需前去绑定");
				return "1";
			}			
		}else{
			logger.info("openid="+openid+"微信用户未入库");
			return "0";
		}
	}

	public WxUser getUser(String openId) {
		List<WxUser> wxList=wxUserDao.findByPropertyName("openid",openId);
		return wxList.get(0);
	}

	/**
	 * 绑定用户电话号码
	 * @param wxUser
	 * @param telphone
	 */
	@Transactional
	public void bindUser(WxUser wxUser, String telphone) {
		List<WxUser> wxList=wxUserDao.findByPropertyName("openid",wxUser.getOpenid());
		if(wxList.size()>0){
			WxUser wUser=wxList.get(0);
			wUser.setTelephone(telphone);
			wxUserDao.save(wUser);
			logger.info("wxUser.getOpenid()="+wxUser.getOpenid()+",telphone="+telphone+"绑定成功");
		}
	}
	
	public boolean isQiandao(WxUser wxUser) {
		String sql="select count(*) from wechat_qiandao where userId="+wxUser.getId()+" and date(qiandaoTime)=curdate()";
		if(jdbcTemplate.queryForInt(sql)==0){
			return false;
		}else{
			return true;
		}
	}

	public void gotoQiandao(WxUser wxUser) {
		String sql="insert into wechat_qiandao (userId,qiandaoTime) values ("+wxUser.getId()+",now())";
		jdbcTemplate.update(sql);
	}
	
	public void gotoTuCao(WxUser wxUser,String content) {
		
		if(!ChinaeseUtil.isChineseChar(content)){
			try {
				content=new String(content.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		String sql="insert into wechat_tucao (userId,tucaoContent,tucaoTime) values("+wxUser.getId()+",'"+content+"2',now());";
		jdbcTemplate.update(sql);
	}

	public WxUser getUserByUserId(String userId) {
		WxUser user=wxUserDao.get(Integer.parseInt(userId));
		return user;
	}
	public WxUser getUserByUserId(Integer userId) {
		WxUser user=wxUserDao.get(userId);
		return user;
	}

	/**
	 * 订单结算，更新用户消费额度
	 * @param order
	 */
	@Transactional
	public void updateUser(Order order) {
		WxUser user=wxUserDao.get(order.getUserId());
		user.setIsConsume((short)1);
		user.setConsumeTotal(user.getConsumeTotal()+order.getOrderPrice());
		user.setConsumeCounts(user.getConsumeCounts()+1);
		wxUserDao.save(user);
	}

	@Transactional
	public void saveUser(WxUser wxUser) {
		wxUserDao.save(wxUser);
	}

}
